﻿using System;
using System.ComponentModel.DataAnnotations;

namespace zijian666.ComponentModel.DataAnnotations;

/// <summary>
/// 取值范围必须是枚举已定义的值
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class EnumAttribute : ValidationAttribute
{
    public EnumAttribute()
    {
        ErrorMessage = "参数 {0} 值不在允许范围";
    }

    public override bool IsValid(object value)
    {
        if (value is null)
        {
            return true;
        }
        return value is Enum && Enum.IsDefined(value.GetType(), value);
    }
}
